#include <rtthread.h>
#include <rtdevice.h>
#include "multi_button.h"
#include "waring.h"
#include "keyapp.h"
#include <board.h>

#define vers "buttonVer_0.0.1"

static struct button YLBD_btn;
static struct button key_btn;


#define YLBD_BUTTON_PIN GET_PIN(B, 9)

static uint8_t YL_button_read_pin(void)
{
    return rt_pin_read(YLBD_BUTTON_PIN);
}



void button_callback(void *btn)
{
    uint32_t btn_event_val;
    rt_uint8_t keyVal;
    void get_key_val(rt_uint8_t keyval);

    btn_event_val = get_button_event((struct button *)btn);
    if(btn==&YLBD_btn)
    {
        keyVal = 0;
    }
    get_key_val(keyVal);

    switch(btn_event_val)
    {
    case PRESS_DOWN:
        rt_kprintf("button press down\n");
        break;

    case PRESS_UP:
        rt_kprintf("button press up\n");
        break;

    case PRESS_REPEAT:
        rt_kprintf("button press repeat\n");
        break;

    case SINGLE_CLICK:
        rt_kprintf("button single click\n");
        break;

    case DOUBLE_CLICK:
        rt_kprintf("button double click\n");
        break;

    case LONG_RRESS_START:
        rt_kprintf("button long press start\n");
        break;

    case LONG_PRESS_HOLD:
        rt_kprintf("button long press hold\n");
        break;

    case LONG_PRESS_UP:
        rt_kprintf("button long press up\n");
        break;
    }

//    if(btn==&YLBD_btn)
//    {
//        presskey_process();
//        rt_kprintf("YLBD_btn button single click\n");
//        return;
//    }

//    if(btn==&key_btn)
//    {
//        rt_kprintf("key_btn button single click\n");
//        return;
//    }

}

void btn_thread_entry(void* p)
{
    while(1)
    {
        /* 5ms */
        rt_thread_delay(RT_TICK_PER_SECOND/200);
        button_ticks();
    }
}

int multi_button_test(void)
{
    rt_thread_t thread = RT_NULL;

    /* Create background ticks thread */
    thread = rt_thread_create("btn", btn_thread_entry, RT_NULL, 512, 10, 10);
    if(thread == RT_NULL)
    {
        return RT_ERROR;
    }
    rt_thread_startup(thread);

    /* low level drive */
    rt_pin_mode  (YLBD_BUTTON_PIN, PIN_MODE_INPUT_PULLUP);
    button_init  (&YLBD_btn, YL_button_read_pin, PIN_LOW);
    button_attach(&YLBD_btn, SINGLE_CLICK,     button_callback);
    button_attach(&YLBD_btn, LONG_PRESS_HOLD,     button_callback);
    button_attach(&YLBD_btn, LONG_PRESS_UP,     button_callback);
    button_start (&YLBD_btn);



    rt_kprintf("Independent keys %s upload success!\n",vers);

    return RT_EOK;
}

INIT_APP_EXPORT(multi_button_test);
